<?php


namespace App\HttpController;


use EasySwoole\EasySwoole\Logger;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\HttpAnnotation\Exception\Annotation\ParamValidateError;
use Throwable;

/**
 * Class ExceptionHandler
 * @package App\HttpController
 */
class ExceptionHandler
{
    /**
     * @param Throwable $exception
     * @param Request $request
     * @param Response $response
     */
    public static function handle(Throwable $exception, Request $request, Response $response)
    {
        $value = $exception->getMessage();
        $statusCode = 500;
        if ($exception instanceof ParamValidateError) {
            $statusCode = 400;
            $value = $exception->getValidate()->getError()->getErrorRuleMsg();
        }

        if ($statusCode == 500){
            Logger::getInstance()->error('500报错--->' . $exception->getFile() . '--' . $exception->getLine() . '--' . $exception->getMessage());
        }

        static::writeJson($response, $statusCode, null, $value);
    }

    /**
     * 返回json数据
     * @param Response $response
     * @param int $statusCode
     * @param null $result
     * @param null $msg
     * @return bool
     */
    public static function writeJson(Response $response, int $statusCode = 200, $result = null, $msg = null): bool
    {
        if (!$response->isEndResponse()) {
            /*if (is_array($result)) {
                // 将数组中下划线样式的键转换为驼峰式的键
                $result = DataConversion::getInstance()->convertToHump($result);
            }*/

            $data = Array(
                "code" => $statusCode,
                "result" => $result,
                "msg" => $msg
            );

            $response->write(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

            $response->withStatus($statusCode);

            return true;
        } else {
            return false;
        }
    }
}